Conditional (computer programming)
part 18/26 · 46.2 KB total
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
Case and switch statements
Switch statements (in some languages, case statements or multiway branches) compare a given value with specified constants and take action according to the first constant to match. There is usually a provision for a default action ('else','otherwise') to be taken if no match succeeds. Switch statements can allow compiler optimizations, such as lookup tables. In dynamic languages, the cases may not be limited to constant expressions, and might extend to pattern matching, as in the shell script example on the right, where the '*)' implements the default case as a regular expression matching any string.
| Pascal : | C : | Shell script : |
|---|---|---|
| case someChar of 'a' : actionOnA ; 'x' : actionOnX ; 'y' , 'z' : actionOnYandZ ; else actionOnNoMatch ; end ; | switch ( someChar ) { case 'a' : actionOnA ; break ; case 'x' : actionOnX ; break ; case 'y' : case 'z' : actionOnYandZ ; break ; default : actionOnNoMatch ; } | case $someChar in a ) actionOnA ; ;; x ) actionOnX ; ;; [ yz ]) actionOnYandZ ; ;; * ) actionOnNoMatch ;; esac |
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────